<template>
  <div class="staff-management">
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon total">
                <el-icon><User /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ staffStats.total }}</div>
                <div class="stats-label">总员工</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon online">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ staffStats.online }}</div>
                <div class="stats-label">在线员工</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon working">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ staffStats.working }}</div>
                <div class="stats-label">工作中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-content">
              <div class="stats-icon departments">
                <el-icon><OfficeBuilding /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ staffStats.departments }}</div>
                <div class="stats-label">部门数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和操作栏 -->
    <el-card shadow="never" class="search-card">
      <div class="search-container">
        <div class="search-left">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索员工姓名、工号"
            style="width: 300px"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="searchForm.department" placeholder="部门" style="width: 150px" clearable>
            <el-option label="全部" value="" />
            <el-option label="洗护部" value="WASHING" />
            <el-option label="熨烫部" value="IRONING" />
            <el-option label="包装部" value="PACKING" />
            <el-option label="配送部" value="DELIVERY" />
            <el-option label="客服部" value="SERVICE" />
          </el-select>
          <el-select v-model="searchForm.status" placeholder="状态" style="width: 120px" clearable>
            <el-option label="全部" value="" />
            <el-option label="在职" value="ACTIVE" />
            <el-option label="离职" value="INACTIVE" />
            <el-option label="请假" value="LEAVE" />
          </el-select>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </div>
        <div class="search-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加员工
          </el-button>
          <el-button @click="handleExport">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 员工列表 -->
    <el-card shadow="never">
      <el-table
        :data="staffList"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="员工信息" min-width="200">
          <template #default="{ row }">
            <div class="staff-info">
              <el-avatar :src="row.avatar" :size="40">
                {{ row.name?.charAt(0) }}
              </el-avatar>
              <div class="staff-detail">
                <div class="staff-name">{{ row.name }}</div>
                <div class="staff-id">工号: {{ row.employeeId }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="position" label="职位" width="120" />
        <el-table-column prop="department" label="部门" width="100">
          <template #default="{ row }">
            <el-tag :type="getDepartmentType(row.department)">
              {{ getDepartmentText(row.department) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
        <el-table-column prop="hireDate" label="入职日期" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-dropdown>
              <el-button type="primary" link>
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleSchedule(row)">
                    <el-icon><Calendar /></el-icon>排班管理
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleSalary(row)">
                    <el-icon><Money /></el-icon>薪资记录
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleLeave(row)" divided>
                    <el-icon><SwitchButton /></el-icon>请假申请
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 员工详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="staffFormRef"
        :model="staffForm"
        :rules="staffFormRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工姓名" prop="name">
              <el-input v-model="staffForm.name" :disabled="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工号" prop="employeeId">
              <el-input v-model="staffForm.employeeId" :disabled="isView" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="staffForm.phone" :disabled="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="staffForm.email" :disabled="isView" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-select v-model="staffForm.department" :disabled="isView" style="width: 100%">
                <el-option label="洗护部" value="WASHING" />
                <el-option label="熨烫部" value="IRONING" />
                <el-option label="包装部" value="PACKING" />
                <el-option label="配送部" value="DELIVERY" />
                <el-option label="客服部" value="SERVICE" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="staffForm.position" :disabled="isView" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入职日期" prop="hireDate">
              <el-date-picker
                v-model="staffForm.hireDate"
                type="date"
                :disabled="isView"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基本工资" prop="baseSalary">
              <el-input-number
                v-model="staffForm.baseSalary"
                :min="0"
                :disabled="isView"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="地址" prop="address">
          <el-input
            v-model="staffForm.address"
            type="textarea"
            :rows="3"
            :disabled="isView"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="staffForm.remark"
            type="textarea"
            :rows="3"
            :disabled="isView"
          />
        </el-form-item>
      </el-form>
      <template #footer v-if="!isView">
        <el-button @click="detailVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getStaffList,
  getStaffStats,
  createStaff,
  updateStaff,
  deleteStaff,
  exportStaff
} from '@/api/laundry'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const staffList = ref([])
const selectedStaff = ref([])
const detailVisible = ref(false)
const isView = ref(false)
const dialogTitle = ref('')

// 统计数据
const staffStats = ref({
  total: 125,
  online: 89,
  working: 67,
  departments: 5
})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  department: '',
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 员工表单
const staffForm = reactive({
  id: null,
  name: '',
  employeeId: '',
  phone: '',
  email: '',
  department: '',
  position: '',
  hireDate: null,
  baseSalary: 0,
  address: '',
  remark: ''
})

// 表单验证规则
const staffFormRules = {
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' }
  ],
  employeeId: [
    { required: true, message: '请输入工号', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  position: [
    { required: true, message: '请输入职位', trigger: 'blur' }
  ]
}

const staffFormRef = ref()

// 模拟数据
const mockStaffList = [
  {
    id: 1,
    name: '张三',
    employeeId: 'E001',
    avatar: '',
    phone: '13800138001',
    email: 'zhangsan@example.com',
    department: 'WASHING',
    position: '洗护师',
    hireDate: '2023-01-15',
    baseSalary: 5000,
    status: 'ACTIVE',
    address: '北京市朝阳区',
    remark: '工作认真负责'
  },
  {
    id: 2,
    name: '李四',
    employeeId: 'E002',
    avatar: '',
    phone: '13800138002',
    email: 'lisi@example.com',
    department: 'IRONING',
    position: '熨烫师',
    hireDate: '2023-02-20',
    baseSalary: 4800,
    status: 'ACTIVE',
    address: '北京市海淀区',
    remark: '技术熟练'
  }
]

// 获取员工列表
const fetchStaffList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    staffList.value = mockStaffList
    pagination.total = mockStaffList.length
  } catch (error) {
    ElMessage.error('获取员工列表失败')
  } finally {
    loading.value = false
  }
}

// 部门类型
const getDepartmentType = (department) => {
  const types = {
    'WASHING': '',
    'IRONING': 'success',
    'PACKING': 'warning',
    'DELIVERY': 'info',
    'SERVICE': 'danger'
  }
  return types[department] || ''
}

// 部门文本
const getDepartmentText = (department) => {
  const texts = {
    'WASHING': '洗护部',
    'IRONING': '熨烫部',
    'PACKING': '包装部',
    'DELIVERY': '配送部',
    'SERVICE': '客服部'
  }
  return texts[department] || '未知'
}

// 状态类型
const getStatusType = (status) => {
  const types = {
    'ACTIVE': 'success',
    'INACTIVE': 'danger',
    'LEAVE': 'warning'
  }
  return types[status] || ''
}

// 状态文本
const getStatusText = (status) => {
  const texts = {
    'ACTIVE': '在职',
    'INACTIVE': '离职',
    'LEAVE': '请假'
  }
  return texts[status] || '未知'
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchStaffList()
}

// 添加员工
const handleAdd = () => {
  isView.value = false
  dialogTitle.value = '添加员工'
  resetForm()
  detailVisible.value = true
}

// 查看员工
const handleView = (row) => {
  isView.value = true
  dialogTitle.value = '员工详情'
  fillForm(row)
  detailVisible.value = true
}

// 编辑员工
const handleEdit = (row) => {
  isView.value = false
  dialogTitle.value = '编辑员工'
  fillForm(row)
  detailVisible.value = true
}

// 排班管理
const handleSchedule = (row) => {
  ElMessage.info(`${row.name} - 排班管理功能开发中`)
}

// 薪资记录
const handleSalary = (row) => {
  ElMessage.info(`${row.name} - 薪资记录功能开发中`)
}

// 请假申请
const handleLeave = (row) => {
  ElMessage.info(`${row.name} - 请假申请功能开发中`)
}

// 导出
const handleExport = async () => {
  try {
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedStaff.value = selection
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.size = size
  fetchStaffList()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchStaffList()
}

// 表单操作
const resetForm = () => {
  Object.assign(staffForm, {
    id: null,
    name: '',
    employeeId: '',
    phone: '',
    email: '',
    department: '',
    position: '',
    hireDate: null,
    baseSalary: 0,
    address: '',
    remark: ''
  })
}

const fillForm = (row) => {
  Object.assign(staffForm, row)
}

const handleSubmit = async () => {
  try {
    await staffFormRef.value.validate()
    submitLoading.value = true
    
    if (staffForm.id) {
      ElMessage.success('更新成功')
    } else {
      ElMessage.success('添加成功')
    }
    
    detailVisible.value = false
    fetchStaffList()
  } catch (error) {
    if (error !== false) {
      ElMessage.error('操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  staffFormRef.value?.resetFields()
}

// 页面加载
onMounted(() => {
  fetchStaffList()
})
</script>

<style scoped>
.staff-management {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 8px;
  overflow: hidden;
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stats-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.online {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.working {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-icon.departments {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.search-card {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.search-left {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.search-right {
  display: flex;
  gap: 12px;
}

.staff-info {
  display: flex;
  align-items: center;
}

.staff-detail {
  margin-left: 12px;
}

.staff-name {
  font-weight: 500;
  color: #303133;
}

.staff-id {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}
</style> 